import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入我们的路由组件
// import Login from '@/views/login/index'
// import Order from '@/views/order/index'
// import Pay from '@/views/pay/index'
// import Prodetail from '@/views/prodetail/index'
// import Search from '@/views/search/index'
// import SearchList from '@/views/search/list'
//优化打包，异步组件
// 导入我们的路由组件
const Login = ()=> import('@/views/login/index') 
const Order = ()=> import('@/views/order/index') 
const Pay = ()=> import('@/views/pay/index') 
const Prodetail = ()=> import('@/views/prodetail/index') 
const Search = ()=> import('@/views/search/index') 
const SearchList = ()=> import('@/views/search/list') 

import Layout from '@/views/layout/index'
import Home from '@/views/layout/Home'
import Cart from '@/views/layout/Cart'
import Category from '@/views/layout/Category'
import User from '@/views/layout/User'

import store from '@/store/index'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/', 
      component: Layout,
      redirect:'/home' ,//重定向到我们的/home页面
      children: [
        { path: '/home', component: Home },
        { path: '/cart', component: Cart },
        { path: '/category', component: Category },
        { path: '/user', component: User },
      ]
    },
    { path: '/search', component: Search },
    { path: '/searchList', component: SearchList },
    // 动态路由传参，确定是哪一个商品详情
    { path: '/prodetail/:id', component: Prodetail },
    { path: '/pay', component: Pay },
    { path: '/order', component: Order },
  ]
})
// 所有的路由在真正被访问到之前(解析渲染对应组件页面前)，都会先经过全局前置守卫
// 只有全局前置守卫放行了，才会到达对应的页面

// 全局前置导航守卫
// to:   到哪里去，到哪去的完整路由信息对象 (路径，参数)
// from: 从哪里来，从哪来的完整路由信息对象 (路径，参数)
// next(): 是否放行
// (1) next()     直接放行，放行到to要去的路径
// (2) next(路径)  进行拦截，拦截到next里面配置的路径

// 定义一个数组，专门用户存放所有需要权限访问的页面
const authUrl = ['/pay','/order']
// 全局前置导航守卫，拦截页面
router.beforeEach((to,from,next) =>{
  //console.log(to,from,next);
  console.log(authUrl.includes(to.path));
  //1:判断访问的是否是需要权限才能访问的页面
  //看to.path 是否在authUrl 中出现过
  if(!authUrl.includes(to.path)){
    next() //如果访问的是非权限页面，直接放行
    return
  }
  //如果是需要权限才可以访问的页面，需要做判断
  const token = store.getters.token
  console.log(token);
  if(token){
    next()
  }else{
    next('/login')
  }
  
})

export default router
